package org.springblade.modules.admin.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AllArgsConstructor;
import org.springblade.common.cache.DictCache;
import org.springblade.common.config.ProjectApiConfiguration;
import org.springblade.core.launch.constant.TokenConstant;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.core.tool.utils.WebUtil;
import org.springblade.modules.admin.dto.report.WxReportData;
import org.springblade.modules.admin.entity.MaintainMalfunctionWork;
import org.springblade.modules.admin.entity.MaintainReportSend;
import org.springblade.modules.admin.enums.ReportSendStatusEnum;
import org.springblade.modules.admin.service.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import org.springblade.modules.admin.mapper.MaintainReportMapper;
import org.springblade.modules.admin.entity.MaintainReport;

@AllArgsConstructor
@Service
public class MaintainReportServiceImpl extends BaseServiceImpl<MaintainReportMapper, MaintainReport> implements MaintainReportService{

	private final IMaintainPlanContentService planContentService;
	private final IMaintainPlanContentExtService planContentExtService;
	private final IMaintainMalfunctionWorkService malfunctionWorkService;
	private final MaintainReportSendService reportSendService;
	private final ProjectApiConfiguration projectApiConfiguration;

	@Override
	public MaintainReport selectReportByWxPlan(Long planId) {

		MaintainReport wxReport = baseMapper.selectReportByWxPlan(planId);
		if(Func.isEmpty(wxReport)){
			throw new ServiceException("工单信息不存在");
		}

		List<MaintainMalfunctionWork> malfunctionWorks = malfunctionWorkService.listByPlanId(planId);
		if(Func.isEmpty(malfunctionWorks)){
			throw new ServiceException("工单信息不存在");
		}
		List<JSONObject> wxReportDataList = new ArrayList<>(malfunctionWorks.size());
		malfunctionWorks.forEach(e -> {
			if(Func.isBlank(e.getProblemItem())){
				WxReportData wxReportData = new WxReportData();
				wxReportData.setPartsIds(e.getPartsIds());
				wxReportData.setPartsNames(e.getPartsNames());
				wxReportData.setMfDesc(e.getMfDesc());
				wxReportData.setFaultDesc(e.getFaultDesc());
				wxReportData.setPartsOpe(e.getPartsOpe());
				wxReportData.setMfImgUrl(e.getMfImgUrl());
				wxReportData.setFaultImg(e.getFaultImg());
				List<String> faultReasonList = new ArrayList<>();
				if(Func.isNotBlank(e.getFaultReasonItem())){
					Func.toStrList(e.getFaultReasonItem()).forEach(j -> {
						faultReasonList.add(DictCache.getValue("fault_reason",j));
					});
				}
				if(Func.isNotBlank(e.getFaultReasonOtherDesc())){
					faultReasonList.add(e.getFaultReasonOtherDesc());
				}
				if(Func.isNotEmpty(faultReasonList)){
					wxReportData.setFaultReason(String.join(",",faultReasonList));
				}
				wxReportDataList.add((JSONObject) JSONObject.toJSON(wxReportData));
			}
		});
		wxReport.setReportData(wxReportDataList);
		return wxReport;
	}

	@Override
	public IPage<MaintainReport> selectReportPage(IPage<MaintainReport> page, MaintainReport report) {
		return page.setRecords(baseMapper.selectReportPage(page,report));
	}

	@Override
	public List<MaintainReport> selectReportList(MaintainReport report) {
		return baseMapper.selectReportList(report);
	}

	@Override
	public MaintainReport detail(Long reportId) {
		return baseMapper.selectReportDetail(reportId);
	}

	@Override
	public Boolean sendReport(Long reportId) {
		Boolean v = Boolean.FALSE;
		String resultStr = HttpUtil.createPost(projectApiConfiguration.getMaintain() + "/maintain/report/send/"+reportId).header(TokenConstant.HEADER,AuthUtil.getHeader(WebUtil.getRequest())).execute().body();
		if(StringUtil.isNotBlank(resultStr)){
			JSONObject resultJson = JSONObject.parseObject(resultStr);
			if("200".equals(resultJson.getString("code"))){
				v = resultJson.getBoolean("data");
			}
		}
		return v;
	}

	@Override
	public Boolean sendLog(MaintainReportSend send) {
		MaintainReport report = super.getById(send.getReportId());
		send.setRobotStatus(this.getRobotStatus(report.getElevatorId()));
		send.setCreateTime(DateUtil.date());
		send.setCreateUser(AuthUtil.getUserId());
		return reportSendService.save(send);
	}

	@Override
	public Boolean sendLog(Long reportId, Integer contentType, Integer status) {
		MaintainReport report = super.getById(reportId);
		MaintainReportSend send = new MaintainReportSend();
		send.setReportId(reportId);
		send.setContentType(contentType);
		send.setStatus(status);
		send.setCreateUser(AuthUtil.getUserId());
		send.setCreateTime(DateUtil.date());
		send.setRobotStatus(this.getRobotStatus(report.getElevatorId()));
		return reportSendService.save(send);
	}

	@Override
	public Boolean sendLog(Long reportId, Integer contentType, Integer status, Long userId) {
		MaintainReport report = super.getById(reportId);
		MaintainReportSend send = new MaintainReportSend();
		send.setReportId(reportId);
		send.setContentType(contentType);
		send.setStatus(status);
		send.setCreateUser(userId);
		send.setCreateTime(DateUtil.date());
		send.setRobotStatus(this.getRobotStatus(report.getElevatorId()));
		return reportSendService.save(send);
	}

	@Override
	public List<MaintainReportSend> selectReportSendLog(Long reportId) {
		return baseMapper.selectReportSendLog(reportId);
	}

	@Override
	public void downExcel(MaintainReport report, List<List<String>> rows) {
		List<MaintainReport> reportList = baseMapper.selectReportExcelList(report);
		reportList.forEach(e -> {
			List<String> row = new ArrayList<>(12);
			row.add(Convert.toStr(e.getId()));
			row.add(Convert.toStr(e.getReportUserName()));
			row.add(Convert.toStr(e.getReportUserRole()));
			row.add(Convert.toStr(ReportSendStatusEnum.getName(e.getSendStatus())));
			row.add(DateUtil.format(e.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
			row.add(Convert.toStr(e.getPlanId()));
			row.add(Convert.toStr(e.getBuildingName()));
			row.add(Convert.toStr(e.getElevatorAddress()));
			row.add(Func.isNotEmpty(e.getWorkOrderType()) ? e.getWorkOrderType() == 1 ? "内部整改":"客户报障" : "--");
			row.add(DateUtil.format(e.getPlanFinishTime(),"yyyy-MM-dd HH:mm:ss"));
			rows.add(row);
		});
	}

	private Integer getRobotStatus(Long elevatorId){
		Integer v = 2;
		String result = HttpUtil.createGet(projectApiConfiguration.getMaintain() + "/repair/robot/status/" + elevatorId).header(TokenConstant.HEADER,AuthUtil.getHeader(WebUtil.getRequest())).execute().body();
		if(StringUtil.isNotBlank(result)){
			JSONObject resultJson = JSONObject.parseObject(result);
			if(resultJson.getString("code").equals("200")){
				v = resultJson.getBoolean("data") ? 1 : 2;
			}
		}
		return v;
	}

}
